<template>
  <jm-modal-view :config="config" @checkData="(obj) => checkData(obj)" ref="jm_modal_view">

    <!-- ================= 弹窗 插槽 ======================= -->
    <template #dialog_slot="scope">
      <data-detail v-if="childData.checkref == 'data_detail'" ref="data_detail" @close-dialog="closeDialog"></data-detail>
      <set-pct v-if="childData.checkref == 'set_pct'" ref="set_pct" @close-dialog="closeDialog"></set-pct>
    </template>

    <!-- 自定义 字段 处理插槽 -->
    <template #roleId="scope">
      <el-tag v-if="scope.row.roleId == 1">总公司</el-tag>
      <el-tag v-if="scope.row.roleId == 2">分公司</el-tag>
      <el-tag v-if="scope.row.roleId == 3">合伙人</el-tag>
      <el-tag v-if="scope.row.roleId == 4">市代理</el-tag>
      <el-tag v-if="scope.row.roleId == 5">区代理</el-tag>
      <el-tag v-if="scope.row.roleId == 6"></el-tag>
      <el-tag v-if="scope.row.roleId == 7"></el-tag>
      <el-tag v-if="scope.row.roleId == 8"></el-tag>
      <el-tag v-if="scope.row.roleId == 9">铺手</el-tag>
    </template>

    <template #onlinePct="scope">
      {{ scope.row.onlinePct }}%
    </template>
    
    <template #userName="scope">
      <div @mouseout.stop="hidePop()">
        <span :ref="el => setPop(el, `pop_ref_${scope.row.id}`)"
        @click.stop="getProfitData(scope.row.id)" 
        style="cursor: pointer;text-decoration: underline;">
          {{ scope.row.userName }}
        </span>
      </div>
    </template>

    <template #isActive="scope">
      <el-tag size="small" type="success" effect="dark" v-if="scope.row.isActive">启用</el-tag>
      <el-tag size="small" type="danger" effect="dark" v-else>禁用</el-tag>
    </template>
    

    <!-- 自定义 表格事件 处理插槽 -->
    <template #table_btn="scope">
      <el-button size="small" @click="resetPwd(scope.row.id)">重置密码</el-button>
      <el-button size="small" @click="setSharePct({ data: scope.row, index: scope._index, checkref: 'set_pct' })">分享比例</el-button>
      <!-- <el-button size="small" @click="setReferencePct({ data: scope.row, index: scope._index, checkref: 'set_pct' })">推荐比例</el-button> -->
    </template>

    <!-- 自定义 弹窗 提交事件 -->
    <template #dialog_btn="scope">
      <el-button v-if="childData.checkref == 'data_detail'" type="primary" 
        @click="childDataOperation({
          checkref: 'data_detail',
          fn: 'submitData'
        })">
        保存
      </el-button>
      <el-button v-if="childData.checkref == 'set_pct'" type="primary" 
        @click="childDataOperation({
          checkref: 'set_pct',
          fn: 'submitData'
        })">
        保存
      </el-button>
    </template>

    <template #easy_search_slot="scope">
      <el-select @change="advSearch()" v-model="scope.adv_search.roleId" 
      style="width: 150px;margin-right: 10px;" size="small" clearable placeholder="请选择角色信息">
        <el-option label="业务经理" :value="3"></el-option>
        <el-option label="市代理" :value="4"></el-option>
        <el-option label="区代理" :value="5"></el-option>
        <el-option label="铺手" :value="9"></el-option>
      </el-select>
    </template>

    <!-- 自定义 筛选条件 插槽 -->
    <template #search_slot="scope">
      <div class="flexbox" style="margin-bottom:10px;">
        <div class="searchContent">企业名称：</div>
        <div class="searchBox" style="width:100%;">
          <el-input @input="advSearch()" placeholder="请输入企业名称" v-model="scope.adv_search.enterpriseName" size="small"></el-input>
        </div>
      </div>
      <div class="flexbox" style="margin-bottom:10px;">
        <div class="searchContent">企业名称：</div>
        <div class="searchBox" style="width:100%;">
          <el-input @input="advSearch()" placeholder="请输入企业名称" v-model="scope.adv_search.valueq" size="small"></el-input>
        </div>
      </div>
    </template>

    <!-- 自定义右键事件框 -->
    <template #contextMenu_slot="scope">
      <div class="clickitem" @click="contextMenuClick(scope.row)">
        <div class="itemleft">功能4</div>
        <div class="itemright"></div>
      </div>
    </template>

  </jm-modal-view>
  
  <div v-if="isshowpop">
    <el-popover
      ref="popoverRef"
      :virtual-ref="vir_pop"
      v-model:visible="isshowpop"
      virtual-triggering
      placement="right"
      width="600"
    >
      <el-table :data="profitData">
        <el-table-column prop="allProfit" label="总收益" />
        <el-table-column prop="monthProfit" label="月收益" />
        <el-table-column prop="yesterDayProfit" label="昨日收益" />
        <el-table-column prop="amount" label="提现金额" />
        <el-table-column prop="realAmount" label="到账金额" />
      </el-table>
    </el-popover>
  </div>
</template>

<script setup>
  import JmModalView from '@/components/Jm_ModalView/JmModalView.vue'
  import DataDetail from './detail.vue'
  import SetPct from './SetPct.vue'


  import { ref, nextTick, inject, unref, watch } from 'vue'
  
  import { useStore } from 'vuex'
  import { useRoute } from 'vue-router';

  const route = useRoute()
  // 注入全局utils工具js
  const $utils = inject('$utils')
  // 注入全局filters工具js
  const $filters = inject('$filters')
  // 定义store
  const store = useStore()

  // 获取到的父组件给子组件的值
  const childData = ref({})
  // 定义ref值
  const data_detail = ref()
  const jm_modal_view = ref()
  const set_pct = ref()


  const popoverRef = ref()
  const isshowpop = ref(false)

  const pop_refs = ref({})
  const vir_pop = ref()

  const setPop = (el, feild) => {
    pop_refs.value[feild] = el
  }

  // 自定义弹出内容ref
  // const data_detail2 = ref()
  
  const profitData = ref([])

  watch(() => route.fullPath, (newPath, oldPath) => {
    let usertype = newPath.split('?')[1].split('=')[1]
    if (usertype == '') {
      usertype = ''
    } else {
      usertype = parseInt(usertype)
    }
    jm_modal_view.value.data_Search({ roleId: usertype })
  })
  
  // 配置模板表单数据
  const config = ref({
    breadcrumb: ['用户列表'],
    // 是否开启右键事件
    openContextMenu: false,
    // 基础增删改查配置
    operation: {
      // 获取表格数据链接
      get_data_url: '/Api/User/GetPagedList',
      // 查询表格详情链接
      get_detaildata_url: '/Api/User/Get',
      // 删除表格数据连接
      del_data_url: '/Api/User/Remove',
      // 编辑列表
      checkref: 'data_detail'
    },
    // 表格内容配置
    table_config: {
      opeWidth: 300,
      column: [
        {
          prop: 'userName',
          label: '账号',
          width: 150,
          slot: true,
          fixed: 'left'
        },
        {
          prop: 'nickName',
          label: '昵称',
          fixed: 'left'
        },
        {
          prop: 'isActive',
          label: '状态',
          slot: true,
          width: 60,
          fixed: 'left'
        },
        {
          prop: 'areaName',
          label: '区域名'
        },
        {
          prop: 'roleId',
          label: '角色',
          slot: true
        },
        {
          prop: 'parent.nickName',
          label: '上级用户'
        },
        {
          prop: 'companySharePct',
          label: '公司分享比例',
          width: 100
        },
        {
          prop: 'sharePct',
          label: '分享比例'
        },
        {
          prop: 'referencePct',
          label: '推荐比例'
        },

        {
          prop: 'deviceQuantity',
          label: '下发设备数'
        },
        {
          prop: 'deviceCount',
          label: '设备安装数'
        },
        {
          prop: 'onlinePct',
          label: '在线率',
          slot: true
        },
        {
          prop: 'allProfit',
          label: '总收益'
        },
        {
          prop: 'monthProfit',
          label: '当月收益'
        },
        {
          prop: 'yesterDayProfit',
          label: '昨日收益'
        },
      ]
    }
    
  })

  // ============================================================================= 自定义事件区域 ====================================================================

  function getProfitData (id) {
    isshowpop.value = false
    vir_pop.value = pop_refs.value[`pop_ref_${id}`]
    $utils.post({
      // GetProfitInfoByUser
      url: '/Api/User/GetProfitInfoByUser',
      params: {
        id: id
      },
      showLoading: true,
      ok: (res) => {
        profitData.value = [res.data]
        isshowpop.value = true
      }
    })
  }
  function hidePop () {
    isshowpop.value = false
  }



  async function setSharePct (obj) {
    childData.value.checkref = obj.checkref
    jm_modal_view.value.showView()
    setDialogWidth('800px')
    setDialogMinWidth('800px')
    let user_info = await getUserInfo(obj.data.id)
    console.log(user_info)
    nextTick(() => {
      set_pct.value.initData({
        data: user_info.data.data,
        feildConfig: {}
      })
    })
  }

  function resetPwd (id) {
    $utils.post({
      url: '/Api/User/ResetPassword',
      params: {
        userId: id
      },
      confirm: true,
      confirmText: '是否重置密码？重置后密码为【123456】！',
      showLoading: true,
      ok: (res) => {
        $utils.message(
          {
            message: '密码修改成功！',
            type: 'success'
          }
        )
      }
    })
  }

  function getUserInfo (id) {
    return $utils.post({
      url: '/Api/User/Get',
      params: {
        id: id
      },
      showLoading: true,
      noasync: true
    })
  }


  // ================================================================================================================================================================

  // 设置弹窗宽度
  function setDialogWidth (str) {
    config.value.dialog_width = str
  }
  // 设置弹窗宽度
  function setDialogMinWidth (str) {
    config.value.dialog_min_width = str
  }
  
  // 保存数据提交方法
  function childDataOperation(obj) {
    // 自定义入参可为空
    let resData = {}
    eval(`${obj.checkref}.value.${obj.fn}({
      data: ${JSON.stringify(resData)}
    })`)
  }

  // 公共模板返回数据emit事件
  async function checkData(obj) {
    childData.value = obj
    await nextTick()
    const resData = obj.data
    switch (obj.checkref) {
      case 'data_detail':
        setDialogWidth('900px')
        setDialogMinWidth('900px')
      break
      default: break;
    }
    eval(`${obj.checkref}.value.${obj.fn}({
      data: ${JSON.stringify(resData)},
      type: obj.type
    })`)
  }

  // 关闭弹窗事件
  function closeDialog(flag) {
    jm_modal_view.value.closeDialog(flag)
  }
  
  // ----------------- 右键点击选择菜单事件 -------------------------
  function contextMenuClick(item) {
    console.log(item)
    store.commit('set_pop_attr', {
      pop_show: false
    })
  }

  // 
  // function diyBtn(obj) {
  //   const sendobj = {
  //     data: obj.data,
  //     checkref: obj.checkref,
  //     fn: 'initData'
  //   }
  //   jm_modal_view.value.diyBtnFn(sendobj)
  // }
  // 高级筛选条件传入并搜索
  function advSearch() {
    // jm_modal_view.value.advSearch()
  }

</script>

<style scoped>

</style>